package com.my.study.net.transfer;

import com.my.study.io.StreamUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Carlos
 * @version 1.0
 * @Description 服务端 - 接收文件，成功后发送“收到图片”
 * @date 2021/7/3 22:03
 **/
@Slf4j(topic = "c.TCPFileUploadServer")
public class TCPFileUploadServer {

    public static void main(String[] args) throws IOException {
        // 服务端监听本机的8888端口
        ServerSocket serverSocket = new ServerSocket(8888);
        log.debug("服务端在8888端口监听....");
        //  等待客户端连接
        Socket socket = serverSocket.accept();

        //===============================获取客户端发送的文件数据
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        byte[] bytes = StreamUtils.streamToByteArray(bis);

        // 写入磁盘
        String path = "D:/file/ReentrantLock3.png";
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path));
        bos.write(bytes);
        bos.close(); // 写入磁盘


        //===============================向客户端发送收到图片的消息
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        writer.write("收到图片");
        writer.flush();
        socket.shutdownOutput();


        // 关闭流
        writer.close();
        bis.close();
        socket.close();
        serverSocket.close();

    }

}
